declare var config;
class Main extends egret.DisplayObjectContainer {
    private static _instance: Main = null;
    public static _parent: egret.DisplayObjectContainer;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.addedToStage, this);
    }

    private addedToStage() {
        var vm = new ViewManager();

        Main._parent = this;
        this.onAddToStage();
        //游戏全局倒计时
        let timer: egret.Timer = new egret.Timer(1000);
        timer.addEventListener(egret.TimerEvent.TIMER, this.update, Main._instance);
        timer.start();
    }




    private onAddToStage() {

        GameData.initData();

        this.runGame().catch(e => {
            console.log(e);
        })

    }


    private getUserInfo() {
        var _that = this;
        return new Promise((reslove, reject) => {
            GameData.tvmid = utils.getQueryString('tvmid');
            GameData.token = utils.getQueryString("token");
            if (GameData.tvmid && GameData.token) {
                user_info = {
                    'nickname': 'debug_name'
                };
                utils.setCookie('tvmid', GameData.tvmid);
                utils.setCookie('apptoken', GameData.token);
                user_info['tvmid'] = GameData.tvmid;
                user_info['apptoken'] = GameData.token;
                reslove();
            } else {
                tvm.getUserInfo().then((data) => {
                    user_info = data;
                    // utils.setCookie('tvmid', data.tvmid);
                    // utils.setCookie('apptoken', data.token);
                    var expire_time = utils.getCookie("login_apptoken_expire_time");
                    var login_apptoken = utils.getCookie("apptoken");
                    var curTime = new Date().getTime();
                    if (login_apptoken && expire_time != null && curTime < Number(expire_time)) {
                        GameData.tvmid = data.tvmid;
                        GameData.token = login_apptoken;
                        utils.setCookie('tvmid', GameData.tvmid);
                        utils.setCookie('apptoken', GameData.token);
                        user_info['tvmid'] = GameData.tvmid;
                        user_info['apptoken'] = GameData.token;
                        reslove();
                    } else {
                        try {
                            _that.login(data).then(function () {
                                reslove();
                            });

                        } catch (error) {
                            return false;
                        }
                    }
                }).catch(function () {
                    reject();
                    Main._parent.addChild(NoticeView.getInstance());
                    NoticeView.getInstance().noticeMsg = "用户身份验证失败，请尝试重新进入";
                    NoticeView.getInstance().callback = function () {
                        tvm.closeH5();
                    };
                });
            }
        })
    }

    //登录
    private async login(data: any) {
        try {
            // 1. 预登陆
            var pre_login_data = await this.pre_login(data);
            // 2.判断是否是新人
            if (pre_login_data['is_home'] == 1) { // 2.1 有家园 不是新人

                // 2.1.1 调统一登录接口
                var home_data = await this.safe_login(pre_login_data['apptoken']);


                var expire_time = Number(home_data['create_time']) + Number(home_data['expire_time']);
                if (expire_time.toString().length == 10) {
                    expire_time *= 1000;
                }
                utils.setCookie('tvmid', home_data["tvmid"]);
                utils.setCookie('apptoken', home_data['apptoken']);
                utils.setCookie('login_apptoken_expire_time', expire_time.toString());

                GameData.tvmid = home_data["tvmid"];
                GameData.token = home_data['apptoken'];
                user_info['tvmid'] = GameData.tvmid;
                user_info['apptoken'] = GameData.token;

                GameData.is_tiyan = false;
            } else { // 2.2 没有家园 是新人
                GameData.is_tiyan = true;
            }
        } catch (e) {
            Main._parent.addChild(NoticeView.getInstance());
            NoticeView.getInstance().noticeMsg = "用户身份验证失败，请尝试重新进入";
            NoticeView.getInstance().callback = function () {
                tvm.closeH5();
            };
        }

    }

    //预登录
    private pre_login(data: any) {
        var _that = this;
        return new Promise((resolve, reject) => {
            var param = {
                tvmid: data.tvmid,
                apptoken: data.token
            }
            CurlUtil.curl(config.GoldHomeApi + "/login/app_pre_login", param).then(function (data: any) {
                if (data['status'] == "success") {
                    data = data['data'];
                    resolve(data);
                } else {
                    reject({ name: "pre_login", code: data['code'] });
                }
            }).catch(function () {
                reject({ name: "pre_login" });
            });
        })
    }

    //家园登录
    private safe_login(pre_apptoken: string) {
        var _that = this;
        return new Promise((resolve, reject) => {
            var param = {
                pre_apptoken: pre_apptoken
            }
            CurlUtil.curl(config.GoldHomeApi + "/login/login", param).then(function (data: any) {
                if (data['status'] == "success") {
                    data = data['data'];
                    resolve(data);
                } else {
                    reject({ name: "safe_login", code: data['code'] });
                }
            }).catch(function () {
                reject({ name: "safe_login" });
            });
        })
    }

    private async runGame() {

        await this.loadResource();

        this.getUserInfo().then(() => {
            this.createGameScene();
            Toast.init();
        });

        // <begin> -- forWX
        // this.getWXInfo().then(() => {
        //     this.createGameScene();
        //     Toast.init();
        // });
        // </begin>

    }

    private async getWXInfo() {
        return new Promise(function (t, i) {
            // <begin>
            // wx.login({
            //     success: (res) => {
            //       console.log(res);
            //         if (res.code) {
            //             CurlUtil.curl(config.GoldHomeApi + '/login/minigame_pre_login', {
            //                 appid: config.APPID,
            //                 code: res.code
            //             }).then((res) => {
            //                 switch (res.code) {
            //                     case 200:
            //                         if (res.data.is_home == 1) {
            //                             //家园用户
            //                             CurlUtil.curl(config.GoldHomeApi + '/login/login', {
            //                                 pre_apptoken: res.data.apptoken
            //                             }).then((res) => {
            //                                 if (res.code == 200) {
            //                                   wx.setStorageSync('apptoken', res.data.apptoken)
            //                                   wx.setStorageSync('tvmid', res.data.tvmid)
            //                                     t(res.data);
            //                                 } else {
            //                                     wx.showModal({
            //                                         title: '提示',
            //                                         content: '登录失败!',
            //                                     });
            //                                     i();
            //                                 }
            //                             })
            //                         } else {
            //                             //TODO 微信玩法
            //                             GameData.is_tiyan = true;
            //                             // 游客模式只记录预登陆apptoken 后面用
            //                             wx.setStorageSync('apptoken', res.data.apptoken);
            //                             t();
            //                         }
            //                         break;
            //                     case 1003:
            //                         //TODO 微信玩法
            //                         break;
            //                     default:
            //                         wx.showModal({
            //                             title: '提示',
            //                             content: '接口异常！',
            //                         })
            //                         break;
            //                 }

            //             })
            //         }
            //     }
            // })
            // </begin>
        })
    }

    private async loadResource() {
        try {

            await RES.loadConfig(config.staticurl + "/resource/default.res.json", config.staticurl + "/resource/");
            await RES.loadGroup("loading");
            // <begin>
            // // 加载排行榜资源
            // window.platform.openDataContext.postMessage({
            // command: "loadRes"
            // });
            // </begin>
            var loadingView = new LoadingUI();
            Main._parent.addChild(loadingView);
            await RES.loadGroup("preload", 0, loadingView);
            Main._parent.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }


    private update(): void {
        if (ViewManager.initView) {
            ViewManager.initView.update();
        }
    }






    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene() {
        GameData.initData();

        ViewManager.initView = new InitView();
        Main._parent.addChild(ViewManager.initView);
        // var jiFen = new JiFenView();
        // Main._parent.addChild(jiFen);
    }


    public static showTop3View(data: any): void {
        if (!ViewManager.top3View) {
            ViewManager.top3View = new TopThreeView(data);
        }
        Main._parent.addChild(ViewManager.top3View);
    }

    public static removeTop3View(): void {
        if (Main._parent.contains(ViewManager.top3View)) {
            Main._parent.removeChild(ViewManager.top3View);
        }
    }


    public static showResetView(type: number = 1) {
        return new Promise((reslove, reject) => {
            if (!ViewManager.resetView) {
                ViewManager.resetView = new ResetAlertView();
            }
            if (!Main._parent.contains(ViewManager.resetView)) {
                ViewManager.resetView.setCallBack(reslove, reject);
                ViewManager.resetView.type = type;
                Main._parent.addChild(ViewManager.resetView);
            } else {
                reject();
            }

        })
    }

    public static removeResetView() {
        if (Main._parent.contains(ViewManager.resetView)) {
            Main._parent.removeChild(ViewManager.resetView);
        }
    }




    public static showRewardView(): void {
        if (!ViewManager.rewardView) {
            ViewManager.rewardView = new RewardView();
        }

        Main._parent.addChild(ViewManager.rewardView);
    }

    public static removeRewardView(): void {
        if (Main._parent.contains(ViewManager.rewardView)) {
            Main._parent.removeChild(ViewManager.rewardView);
        }
    }


    public static showJFView(endTime: number): void {
        if (!ViewManager.jfView) {
            ViewManager.jfView = new JiFenRankView();
        }
        ViewManager.jfView.end_time = endTime;
        Main._parent.addChild(ViewManager.jfView);
    }

    public static removeJFView(): void {
        if (Main._parent.contains(ViewManager.jfView)) {
            Main._parent.removeChild(ViewManager.jfView);
        }
    }

    public static removeLastJFView(): void {
        if (Main._parent.contains(ViewManager.lastJFView)) {
            Main._parent.removeChild(ViewManager.lastJFView);
        }
    }

    public static showLastJFView(): void {
        if (!ViewManager.lastJFView) {
            ViewManager.lastJFView = new LastJiFenRankView();
        }
        Main._parent.addChild(ViewManager.lastJFView);
    }

    public static showHelpView(): void {
        if (!ViewManager.helpView) {
            ViewManager.helpView = new HelpAlertView();
        }
        // 1. 请求帮助接口
        if (GameData.rule == undefined || GameData.rule == '') {
            // 网络
            CurlUtil.curl(config.GoldHomeApi + "/dictionary/rules", {}).then((data) => {
                if (data['status'] == 'success') {
                    data = data['data'];
                    var rule = data['chest_odd'];
                    if (rule != undefined && rule != '') {
                        GameData.rule = rule;
                        ViewManager.helpView.text = rule;
                        Main._parent.addChild(ViewManager.helpView);
                    }
                }
            }).catch((err) => {

            });
        } else {
            // 直接弹
            ViewManager.helpView.text = GameData.rule;
            Main._parent.addChild(ViewManager.helpView);
        }
    }

    public static showTooInfoView(data: any): void {
        if (!ViewManager.toolInfoView) {
            ViewManager.toolInfoView = new ToolInfoView();
        }
        Main._parent.addChild(ViewManager.toolInfoView);
        ViewManager.toolInfoView.open(data);
    }

    public static removeTooInfoView(): void {
        Main._parent.removeChild(ViewManager.toolInfoView);
    }


    public static showNoEndView(): void {
        if (!ViewManager.noEndView) {
            ViewManager.noEndView = new NoEndView();
        }
        Main._parent.addChild(ViewManager.noEndView);
    }

    public static removeNoEndView(): void {
        Main._parent.removeChild(ViewManager.noEndView);
    }


}